package jnpf.engine.custom.type;

import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.common.engine.impl.persistence.cache.CachedEntity;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.HistoricActivityInstanceEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @Author:LoveMyOrange
 * @Description:
 * @Date:Created in 2022/5/13 12:08
 */
@Component
public class HistoryActivityInstanceEndedListener implements FlowableEventListener {
    @Override
    public void onEvent(FlowableEvent event) {
        if(event instanceof FlowableEntityEventImpl){
            FlowableEntityEventImpl flowableEntityEvent=(FlowableEntityEventImpl)event;
            HistoricActivityInstanceEntity historicActivityInstanceEntity = (HistoricActivityInstanceEntity) flowableEntityEvent.getEntity();

            if(historicActivityInstanceEntity.getActivityType().equals("userTask")){
                String taskId = historicActivityInstanceEntity.getTaskId();
                HistoricTaskInstance historicTaskInstance = CommandContextUtil.getEntityCache().findInCache(HistoricTaskInstance.class, taskId);
                if(historicTaskInstance!=null){
                    historicActivityInstanceEntity.setAssignee(historicTaskInstance.getAssignee());
                }
            }


        }
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
